from fastapi import (FastAPI, Query, BackgroundTasks)
from fastapi.openapi.models import RequestBody
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
from tooles.ted.reader import Worker
import os,uvicorn
from tooles.coze.worker import Worker as Worker_coze

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

worker = Worker()
# backgroundTasks = BackgroundTasks()
worker_coze = Worker_coze()

@app.post("/api/punc")
async def punc(params: dict):
    """
    给文本添加合适的标题
    :param params: {"text":"文本"}
    :return:返回处理后的值
    """
    try:
        text = params.get("text")
        res = worker_coze.proc("chat2text",f"请给这段话加上合适的标点：{text}")
        return {"message": res, "error":""}
    except Exception as e:
        return {"message": "", "error": e}

@app.get("/api/ted")
async def test(background_tasks: BackgroundTasks, url: str = Query(None)):
    audio_fn = worker.get_audio_fn(url)
    if os.path.exists(audio_fn):
        return RedirectResponse(url=f"/{audio_fn}")
    else:
        background_tasks.add_task(worker.proc,url)
        print(background_tasks.tasks)
        return {"message": f"/{audio_fn}"}


if __name__ == "__main__":
    uvicorn.run("api:app", host="0.0.0.0", port=8000,  reload=True) 
    # 命令行执行 uvicorn api:app --reload 也可以启动服务